﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AndroidTools
{
    public partial class FrmIDA : Form
    {
        public FrmIDA()
        {
            InitializeComponent();
        }



        #region 拖APK
        private void FrmIDA_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            string path = Global.apkPath = files[0];
            Global.apkInfo = new ApkInfo(path);
            txtPackage.Text = Global.apkInfo.manifestInfo.PackageName + "/" + Global.apkInfo.manifestInfo.MainActivity;
        }


        private void FrmIDA_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
                string file = files[0];

                if (new FileInfo(file).Extension.ToLower().Equals(".apk"))
                {
                    e.Effect = DragDropEffects.Copy;
                    return;
                }
                e.Effect = DragDropEffects.None;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
        #endregion


        private void FrmIDA_Load(object sender, EventArgs e)
        {
            GetDeviceInfo();
        }


        /// <summary>
        /// 获取设备信息
        /// </summary>
        private void GetDeviceInfo()
        {
            Global.devices = ApkHelper.GetDeviceInfo();
            cmbDevices.Items.Clear();
            cmbDevices.Text = "无设备";

            if (Global.devices.Count > 0)
            {
                foreach (Device device in Global.devices)
                {
                    cmbDevices.Items.Add(device.Name);
                }
                cmbDevices.SelectedIndex = 0;
                Global.selectDeviceIdx = 0;
            }
        }

        private void BtnRefreshDevices_Click(object sender, EventArgs e)
        {
            GetDeviceInfo();
        }

        private void BtnSelectASPath_Click(object sender, EventArgs e)
        {
            FrmFile frmFile = new FrmFile();
            frmFile.StartPosition = FormStartPosition.CenterScreen;
            frmFile.frmIDA = this;
            frmFile.ShowDialog();
        }


        private void CmbDevices_SelectedIndexChanged(object sender, EventArgs e)
        {
            Global.selectDeviceIdx = cmbDevices.SelectedIndex;
        }

        public void SettingTxtAndSerPath()
        {
            txtAndSerPath.Text = Global.androidServerPath;
        }

        public void Print(string txt)
        {
            txtPrint.Text += txt + "\r\n";
        }

        private void StartDebug_Click(object sender, EventArgs e)
        {
            string deviceName = Global.devices[Global.selectDeviceIdx].Name;

            Print("开始调试中。。。");


            Print("检查端口" + numPort.Value + "是否被占用");
            // 查询端口是否被占用
            string pid = ApkHelper.Netstat(deviceName, (int)numPort.Value);
            if (pid == "")
            {
                Print("端口" + numPort.Value + "未被占用");
            }
            else
            {
                Print("端口" + numPort.Value + "被占用,准备结束该端口进程");
                ApkHelper.Kill(deviceName, pid);
                Print("进程" + pid + "结束成功");
            }

            Print("运行android_server");
            // 运行android_server
            ApkHelper.ADB(deviceName, string.Format(".{0} -p" + numPort.Value, Global.androidServerPath), true);
            // 查询是否启动成功，检查端口即可

            // 端口转发
            // adb forward tcp:23946 tcp:23946
            ApkHelper.Forward((int)numPort.Value);

            // 打开需要调试的APP
            // adb shell am start -D -n com.test.jni_03/.MainActivity
            ApkHelper.ADB(deviceName, string.Format("am start -D -n {0}/{1}", Global.apkInfo.manifestInfo.PackageName, Global.apkInfo.manifestInfo.MainActivity), true);

            // 获取APP进程


            // 手动打开IDA

            // 运行jdb命令
        }

        private void FrmIDA_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void OpenDDMS_Click(object sender, EventArgs e)
        {
            Helper.Cmd("ddms", true);
            Helper.Cmd("monitor", true);
            Print("运行打开ddms命令");
        }

        private void RunJdb_Click(object sender, EventArgs e)
        {
            Print("运行jdb命令");
            // 运行jdb命令
            Helper.Cmd(string.Format("jdb -connect com.sun.jdi.SocketAttach:hostname=127.0.0.1,port={0}", numDebugPort.Value), true);

        }

        private void btnInstall_Click(object sender, EventArgs e)
        {
            if (Global.apkPath == "")
            {
                return;
            }

            string cmd = string.Format("adb install \"{0}\"", Global.apkPath);
            Print("运行安装APK命令");
            string res = Helper.Cmd(cmd, false);
            Print(res);
        }
    }
}
